#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys, gobject, os, mimetypes, re
import ConfigParser
import easygtk
try:
    import pygtk
    pygtk.require("2.0")
except:
      pass
try:
    import gtk
    import gtk.glade
except:
    print "Error"
    sys.exit(1)

# Settings
settings="HOME"
if os.sys.platform.startswith("win"): settings="USERPROFILE"
settings_dir=os.getenv(settings) + os.path.sep + ".yais"
if os.path.exists(settings_dir) == False:
    try:
        print "Warning: the settings dir does not exists"
        os.mkdir(settings_dir)
    except:
        print "Error: impossible to get the settings dir !"
        sys.exit(1)
    
class YAIS:
    """Main window !"""
    def __init__(self):
        self.xml = gtk.glade.XML('yais.glade')
        #Auto connecting events
        self.xml.signal_autoconnect(self)
        
        self.window = self.xml.get_widget('yais')
        self.window.show_all()
        
        self.menu=self.xml.get_widget('menuadd')
        print "Note: YAIS main window loaded"
        
        self.maxstep=4
        self.step=1
        
        # Load settings
        print settings_dir + os.path.sep + "settings.ini"
        #self.settings=ConfigParser.Config(settings_dir + os.path.sep + "settings.ini")
        
        self.connect_events()
    
    def connect_events(self):
        """Declaring all events"""
        self.window.connect("delete-event", self.event_quit)
        
        self.xml.get_widget('addrepert').connect('activate', self.menu_addrepert)
        self.xml.get_widget('addfile').connect('activate', self.menu_addfile)
        
        self.filelistimg=self.xml.get_widget("filelistimg")
        self.filelistimg.hide()
        
        self.next_step=self.xml.get_widget("next_step")
        self.next_step.connect("clicked", self.btn_next_clicked)
        
        self.previous_step=self.xml.get_widget("previous_step")
        self.previous_step.connect("clicked", self.btn_previous_clicked)
        # Initializing widget
        self.previous_step.set_sensitive(False)
        
        self.redimensionner=self.xml.get_widget("redimensionner")
        self.redimensionnerpredef=self.xml.get_widget("redimensionnerpredef")
        self.redimensionnerperso=self.xml.get_widget("redimensionnerperso")
        self.redimensionnerpersox=self.xml.get_widget("redimensionnerpersox")
        self.redimensionnerpersoy=self.xml.get_widget("redimensionnerpersoy")
        
        self.compress=self.xml.get_widget("compress")
        self.compressformat=self.xml.get_widget("compressformat")
        
        self.destmodif=self.xml.get_widget("destmodif")
        
        self.fileadd=self.xml.get_widget("fileadd")
        self.fileadd.connect("button-release-event", self.btn_fileadd_released)
        
        self.fileremove=self.xml.get_widget("fileremove")
        self.fileremove.connect("button-release-event", self.btn_fileremove_released)
        
        self.cancel_step=self.xml.get_widget("cancel")
        self.cancel_step.connect("clicked", self.btn_cancel_clicked)
        
        self.tabs=self.xml.get_widget("step")
        self.tabs.set_show_tabs(False)
        
        """Now preparing the list"""
        renderer = gtk.CellRendererText()
        
        self.filelisttree = gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING)
        self.filelist=self.xml.get_widget("filelist")
        selection =  self.filelist.get_selection()
        selection.connect('changed', self.btn_filelist_clicked)
        #self.filelist.connect("button-press-event", self.btn_filelist_clicked)
        self.filelist.connect("key-press-event", self.key_filelist_pressed)
        self.filelist.set_reorderable(True)
        self.filelist.set_model(self.filelisttree)
        column = gtk.TreeViewColumn("file", renderer, text=0)
        self.filelist.append_column(column)
        column=gtk.TreeViewColumn("path", renderer, text=1)
        column.set_visible(False)
        self.filelist.append_column(column)
        
        self.redimensionnerlisttree = gtk.ListStore(gobject.TYPE_STRING)
        self.redimensionnerlist=self.xml.get_widget("redimensionnerlist")
        selection =self.redimensionnerlist.get_selection()
        self.redimensionnerlist.set_model(self.redimensionnerlisttree)
        column=gtk.TreeViewColumn("path", renderer, text=0)
        self.redimensionnerlist.append_column(column)
        #self.redimensionnerlist.set_headers_visible(False)
        """Add the list"""
        self.redimensionnerlisttree.append(["64x64"])
        self.redimensionnerlisttree.append(["160x120"])
        self.redimensionnerlisttree.append(["320x240"])
        self.redimensionnerlisttree.append(["640x480"])
        self.redimensionnerlisttree.append(["800x600"])
        self.redimensionnerlisttree.append(["1024x768"])
        selection.connect('changed', self.autofocus)
        
    def event_quit (self, widget=None, event=None):
        """Closing YAIS window"""
        gtk.main_quit()
        print "Note: Closing YAIS"
        sys.exit(1)
        
    def btn_next_clicked (self,widget):
        if (self.step == self.maxstep):
            self.next_step.set_sensitive(False)
            print "Warning: impossible, last step already active : %d" % (self.maxstep)
        else:
            error=False
            if (self.step == 1):
                #Testing step 1
                if (len(self.filelisttree) == 0):
                    easygtk.alert("Aucun fichier sélectionné !")
                    error=True
            elif (self.step == 2):
                if (self.redimensionner.get_active() == True):
                    if (self.redimensionnerperso.get_active() == True):
                        if (re.search(r"^\d+(%?)-\d+\1$", self.redimensionnerpersox.get_text() + "-" + self.redimensionnerpersoy.get_text()) == None):
                            easygtk.alert("Veuillez entrer une taille valide, en pixel, ou avec %")
                            error=True
                    elif (self.redimensionnerpredef.get_active() == True):
                        if (self.redimensionnerlist.get_selection().get_selected()[1] == None):
                            easygtk.alert("Veuillez sélectionner une taille !")
                            error=True
                
            elif (self.step == 3):
                if (self.compress.get_active() == True):
                    if (self.compressformat.get_active() == -1):
                        easygtk.alert("Choisissez un format !")
                        error=True
            if (error is not True):
                self.previous_step.set_sensitive(True)
                self.step=self.step+1
                if (self.step == self.maxstep + 1):
                    self.next_step.set_sensitive(False)
                self.tabs.next_page()
                print "Note: next step %d" % (self.step)
    
    def btn_previous_clicked (self,widget):
        if (self.step == 1):
            self.previous_step.set_sensitive(False)
            print "Warning: impossible, first step already active: %d" % (self.step)
        else:
            self.next_step.set_sensitive(True)
            self.step=self.step-1
            if (self.step == 1):
                self.previous_step.set_sensitive(False)
            self.tabs.prev_page()
            print "Note: previous step %d" % (self.step)
            
    def btn_cancel_clicked (self,widget):
        print "Note: Cancelling"
        self.event_quit()
            
    def btn_fileremove_released (self,widget,event=None):
        print "FileRemove button released"
        selection=self.filelist.get_selection()
        model, treeiter = selection.get_selected()
        if treeiter is not None:
            self.filelisttree.remove(treeiter)
            self.filelistimg.hide()
                     
    def btn_fileadd_released (self,widget,event=None):
        self.menu.popup(None, None, None, event.button, event.time)
        print "FileAdd button released"
        return True
    
    def btn_filelist_clicked (self, widget, event=None):
        selection=self.filelist.get_selection()
        model, treeiter = selection.get_selected()
        if treeiter is not None:
            content = model[treeiter][1]
            print "FileList changed : " + content
            pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(content, 80, 80)
            self.filelistimg.set_from_pixbuf(pixbuf)
            self.filelistimg.show()
            
    def autofocus (self, widget, event=None):
        if (type(widget) == gtk.TreeSelection):
            temp=widget.get_tree_view()
            name=temp.name
        else:
            name=widget.name
        if (re.search(r"^redimensionner(.*)", name)):
            if (type(widget) == gtk.Entry):
                if (len(widget.get_text()) != 0):
                    self.redimensionner.set_active(True)
                    self.redimensionnerperso.set_active(True)
            elif (type(widget) == gtk.TreeSelection):
                selection=temp.get_selection()
                model, treeiter = selection.get_selected()
                if treeiter is not None:
                    self.redimensionner.set_active(True)
                    self.redimensionnerpredef.set_active(True)
            elif (type(widget) == gtk.CheckButton):
                if (widget.get_active() == True):
                    self.redimensionner.set_active(True)
        elif (re.search(r"^compress(.*)", name)):
            self.compress.set_active(True)
        elif (re.search(r"dest(.*)", name)):
            if (type(widget) == gtk.CheckButton):
                self.destmodif.set_active(True)
            if (type(widget) == gtk.Entry):
                if (len(widget.get_text()) != 0):
                    self.destmodif.set_active(True)
            if (type(widget) == gtk.SpinButton):
                self.destmodif.set_active(True)
            
    
    def key_filelist_pressed(self, widget, event=None):
        if (event.keyval == 65535):
            selection=self.filelist.get_selection()
            model, treeiter = selection.get_selected()
            if treeiter is not None:
                self.filelisttree.remove(treeiter)
                self.filelistimg.hide()
    
    def menu_addrepert(self, widget):
        print "FileAdd Menu: Add a repertory"
        self.menu.popdown()
        self.selectrep = gtk.FileSelection(title="Choisissez le dossier")
        self.selectrep.dir_list
        self.selectrep.set_filename("/media/sda6/Stockage Images/Test")
        #self.selectrep.set_filename("C:\Documents and Settings\Administrateur.GROUPE-873084DC\Mes documents\Mes images\Test")
        self.selectrep.ok_button.connect("clicked", self.menu_addrepert_ok)
        self.selectrep.cancel_button.connect("clicked",lambda w: self.selectrep.destroy())
        self.selectrep.show()
        
    def menu_addfile(self, widget):
        print "FileAdd Menu : Add a file"
        self.menu.popdown()
        self.selectfile = gtk.FileSelection(title="Choisissez un fichier")
        self.selectfile.set_filename("/media/sda6/Stockage Images/Test/")
        self.selectfile.ok_button.connect("clicked", self.menu_addfile_ok)
        self.selectfile.cancel_button.connect("clicked",lambda w: self.selectfile.destroy())
        self.selectfile.show()
        
    def menu_addfile_ok (self, widget):
         if (self.selectfile.get_filename()):
             print "FileAdd Menu: File %s" % (self.selectfile.get_filename())
             self.addfile2filelist(os.path.basename(self.selectfile.get_filename()),self.selectfile.get_filename())
             self.selectfile.destroy()
        
    def menu_addrepert_ok(self, w):
        if (self.selectrep.get_filename()):
            print "FileAdd Menu: Repertory %s" % (self.selectrep.get_filename())
            self.addrepertory2filelist(self.selectrep.get_filename())
            self.selectrep.destroy()
        else:
            print "Warning: FileAdd Menu: Repertory not added"
            self.select.destroy()
            
    def addrepertory2filelist(self, rep):
        print "Add repertory 2 filelist"
        rep=os.path.normcase(rep)
        dir=os.listdir(rep)
        dir.sort()
        for files in dir:
            complete=rep + os.path.sep + files
            if os.path.isfile(complete):
                self.addfile2filelist(files, complete)
                
    def addfile2filelist(self, file, complete):
        mime=mimetypes.guess_type(complete)[0]
        if mime != None:
            if (re.search(r"^image/(.*)", mime)):
                self.filelisttree.append([file, complete])
        elif (re.search(r".*\.(jpg|png|jpeg)", file)):
            self.filelisttree.append([file, complete])
        
if __name__ == "__main__":
    hwg = YAIS()
    gtk.main()